#include "AudioMnger.h"
AudioMnger::AudioMnger(string filename){
    currentPos = 0;
    isPlaying = false;
    isRecording = false;

    AudioFile.loadFile(filename);

    vector<float> tmp;
    tmp.clear();
    CurrentComment.setData(tmp);

    Pa_Initialize();
    Pa_OpenDefaultStream(
            &inoutStream, 
            AudioFile.getChannels(), 
            AudioFile.getChannels(),
            paFloat32,
            AudioFile.getSamplerate(),
            paFramesPerBufferUnspecified,
            NULL,
            NULL);
    Pa_StartStream(inoutStream);
}
AudioMnger::~AudioMnger(){
    Pa_StopStream(inoutStream);
    Pa_CloseStream(inoutStream);
    Pa_Terminate();
}
void AudioMnger::_play(){
    isPlaying = true;
    int nFrames = 1024;
    vector<float> temp;
    int inc;
    while(isPlaying){
        inc = AudioFile.getData(&temp, currentPos, nFrames);
        Pa_WriteStream(inoutStream, temp.data(), inc);
        currentPos += inc;

        if (inc < nFrames) isPlaying = false;
        cout << inc << " ";
    }
}
void AudioMnger::play(){
    if (isPlaying)
        return;
    playthrd = new boost::thread(boost::bind(&AudioMnger::_play, this));
    playthrd->join();
}

void AudioMnger::_record(){
    isRecording = true;
    vector<float> tmpv;
    float *tmp = new float[512];
    while(isRecording){
        Pa_ReadStream(inoutStream, tmp, 512);
        for (int i = 0; i != 512; i ++)
            tmpv.push_back(tmp[i]);
    }
    CurrentComment.setData(tmpv);
    delete tmp;
}
void AudioMnger::record(){
    if (isRecording)
        return;
    recordthrd = new boost::thread(boost::bind(&AudioMnger::_record, this));
}

void AudioMnger::save(string filename){
    CurrentComment.saveFile(filename);
}
